<script setup lang="ts">
import { createRuleAPI, getRoleDetailAPI, updateRoleAPI } from '@/apis/card'
import { getTreeListAPI } from '@/apis/system'
import type { getRoleDetail, GetRoleDetailData } from '@/types/card'
import type { RoleData, RoleParams } from '@/types/system'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import type { TreeInstance } from 'element-plus/lib/components/index.js'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const roleForm=ref<RoleParams>({
    roleName:'',
    remark:'',
    perms:[],
    roleId:undefined
})

const activeStep=ref<number>(1)
const roleFormRef=ref<FormInstance>()
const roleRules=ref<FormRules<RoleParams>>({
    roleName: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
      { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    remark: [
      { required: true, message: '请输入角色描述', trigger: 'blur' },
    ]
})

const treeList=ref<RoleData[]>([])
const getTreeList=async ()=>{
    const res=await getTreeListAPI()
    treeList.value=res.data
}
getTreeList()
const addStep=()=>{
    nextStep()
}

const getDateList=ref<GetRoleDetailData>({
    /**
 * 已选择的路由信息
 */
perms: [],
/**
 * 备注
 */
remark: '',
/**
 * 角色id
 */
roleId: '',
/**
 * 角色名称
 */
roleName: '',
/**
 * 当前角色分配人数
 */
userTotal: undefined
})


onMounted(async()=>{
    const res=await getRoleDetailAPI(roleId)
    getDateList.value=res.data as GetRoleDetailData
    console.log('res111',res);
    roleForm.value.roleName=getDateList.value.roleName
    roleForm.value.remark=getDateList.value.remark
    roleForm.value.perms=getDateList.value.perms
    roleForm.value.roleId=+getDateList.value.roleId
    console.log(roleForm.value.perms);

    treeRefs.value.forEach((tree, index)=>{
          tree.setCheckedKeys(roleForm.value.perms[index])
        })
})
const subtractStep=()=>{
  if(activeStep.value===3){
    roleForm.value.perms=[]
  }
  activeStep.value--
}

const treeRefs=ref<TreeInstance[]>([])

const disTreeRefs=ref<TreeInstance[]>([])

const nextStep=async ()=>{
    try{
        if(activeStep.value===1){
            await roleFormRef.value?.validate()
            activeStep.value++
        }else if(activeStep.value===2){
            // roleForm.value.perms=[]
            treeRefs.value.forEach(tree=>{
                const res=tree.getCheckedKeys() as number[]
                
                roleForm.value.perms.push(res)
            })
            if(roleForm.value.perms.flat(Infinity).length===0){
                ElMessage.error('请选择权限')
            }else{
                activeStep.value++
                disTreeRefs.value.forEach((tree, index)=>{
          tree.setCheckedKeys(roleForm.value.perms[index])
        })
            }
        }

    }catch{

    }
}

const router=useRouter()
const confirmAdd=async()=>{
    
    ElMessage({
        type:'success',
        message:'添加角色成功'
    })
    console.log('roleForm.value1111',roleForm.value);
    const res=await updateRoleAPI(roleForm.value)
    console.log('reswc',res);
    // router.back()
    // console.log('res1111',res);
    
}
const route=useRoute()
const roleId:string=route.params.id as string
// console.log('id',id);

</script>

<template>
  <div class="add-role">
    <header class="add-header">
      <el-page-header :content="(roleId)?'编辑角色':'添加角色'" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="activeStep">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <div v-show="activeStep===1" class="form-container">
        <el-form ref="roleFormRef" class="form-box" :model="roleForm" :rules="roleRules">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" type="textarea" />
            </el-form-item>
          </el-form>
        <div class="form">
          角色信息内容
        </div>
      </div>
      <div v-show="activeStep===2"  class="form-container">
        <div class="title">权限配置</div>
        <div class="form">
            <div class="tree-wrapper">
            <div v-for="(item,index) in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree 
                :data="item.children" 
                show-checkbox 
                default-expand-all 
                :node-key="item.id?.toString()"
                :props="{ label: 'title' }" 
                ref="treeRefs"
              />
            </div>
          </div>
        </div>
      </div>
      <div v-show="activeStep===3" class="form-container">
        <div class="title">检查并完成
            <div class="form-container">
                    <el-form ref="roleFormRef" class="form-box" :model="roleForm" :rules="roleRules">
                        <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="roleForm.roleName" />
                        </el-form-item>
                        <el-form-item label="角色描述" prop="remark">
                        <el-input v-model="roleForm.remark" type="textarea" />
                        </el-form-item>
                    </el-form>
                    <div class="form">
                    角色信息内容
                    </div>
            </div>
        <div class="form">
            <div class="tree-wrapper">
            <div v-for="(item,index) in treeList" :key="item.id" class="tree-item">
              <div class="tree-title">{{ item.title }}</div>
              <el-tree 
                :data="item.children" 
                show-checkbox 
                default-expand-all 
                node-key="item.id?.toString()"
                :props="{ label: 'title',disabled:()=>true }" 
                ref="disTreeRefs"
              />
            </div>
        </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button v-if="activeStep>1" @click=subtractStep()>上一步</el-button>
        <el-button v-if="activeStep<3" @click="addStep()" type="primary">下一步</el-button>
        <el-button v-else-if="activeStep===3"  type="primary" @click="confirmAdd()">点击完成</el-button>
            {{ roleForm }}
        </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 30px;
    display: flex;

    .step-container {
      height: 400px;
      width: 200px;
    }

    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;
        }

        .info {
          font-size: 14px;
          color: #666;

          .form-item {
            margin-bottom: 20px;
          }
        }
      }

      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }

  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;

      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }
    }
  }
}
</style>